//
//  GiftCollectionViewCell.m
//  礼物说
//
//  Created by dllo on 16/4/26.
//  Copyright © 2016年 sunzhichao. All rights reserved.
//

#import "GiftCollectionViewCell.h"

@interface GiftCollectionViewCell ()<UITableViewDelegate, UITableViewDataSource, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UIScrollViewDelegate>

@property (nonatomic, retain) BaseView *topView;
@property (nonatomic, retain) NSMutableArray *zhongZhuanArr;
@property (nonatomic, assign) NSInteger selectIndex;
/** 算出有竖排有几个cell 点击会有值*/
@property (nonatomic, assign) NSInteger num;
@property (nonatomic, assign) NSInteger nums;
@property (nonatomic, assign) BOOL isRelate;

@end

@implementation GiftCollectionViewCell

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        
        [self createView];
        [self createTableView];
        [self createCollectionView];
    }
    return self;
}
- (void)dealloc {
    [_zhongZhuanArr release];
    [_topView release];
    [_gitfArr release];
    [_tableView release];
    [_collectionView release];
    [super dealloc];
}

- (void)setGitfArr:(NSMutableArray *)gitfArr {
    if (_gitfArr != gitfArr) {
        [_gitfArr release];
        _gitfArr = [gitfArr retain];
        
        self.zhongZhuanArr = [NSMutableArray arrayWithArray:_gitfArr];
    }
}

#pragma mark - 创建视图
- (void)createView {
    self.topView = [[BaseView alloc] initWithFrame:CGRectMake(0, 0, kWIDTHCELL, kWIDTHS(30))];
    [self.contentView addSubview:_topView];
    [_topView release];
    
//    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kWIDTHS(10), kHEIGHTS(30))];
//    [_topView addSubview:imageView];
//    imageView.image = [UIImage imageNamed:@""];
    
    BaseLabel *lable = [[BaseLabel alloc] initWithFrame:CGRectMake(kWIDTHS(20), 0, kWIDTHS(100), kWIDTHS(30))];
    lable.text = @"送礼神器";
    lable.textColor = [UIColor blueColor];
    [_topView addSubview:lable];
    [lable release];
    
//    UIImageView *imgV = [[UIImageView alloc] initWithFrame:CGRectMake(kWIDTHCELL - kWIDTHS(15), kHEIGHTS(5), kWIDTHS(10), kWIDTHS(20))];
//    [_topView addSubview:imgV];
//    [imgV release];
//    imgV.image = PLACEHOLDER_IMAGE;
}

#pragma mark - 创建TableView 
- (void)createTableView {
    self.tableView = [[BaseTableView alloc] initWithFrame:CGRectMake(0, kWIDTHS(30), kWIDTHS(93), kHEIGHTCELL - 49) style:UITableViewStylePlain];
    [self.contentView addSubview:_tableView];
    [_tableView release];
    
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    self.selectIndex = 0;
    
    [_tableView registerClass:[BaseTableViewCell class] forCellReuseIdentifier:@"tableViewCell"];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _zhongZhuanArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    

    BaseTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"tableViewCell"];
    GiftBeforeModel *model = _zhongZhuanArr[indexPath.row];
    if (kWIDTHCELL < 375) {
        cell.textLabel.font = [UIFont systemFontOfSize:12];
    }
    cell.textLabel.text = model.name;
    cell.textLabel.textAlignment = NSTextAlignmentCenter;
//    cell.textLabel.tag = 1000 + indexPath.row;
//    cell.textLabel.font = [UIFont systemFontOfSize:12];
    cell.textLabel.textColor = [UIColor grayColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if (indexPath.row == _selectIndex) {
        
        cell.textLabel.textColor = UIColorFromRGB(0XFF2D47);
    }
//    UIView *selectedBackgroundView = [[UIView alloc] initWithFrame:cell.frame];
//    selectedBackgroundView.backgroundColor = [UIColor whiteColor];
//    selectedBackgroundView.alpha = 0.8;
//    UILabel *lineLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 5, 40)];
//    lineLabel.backgroundColor = [UIColor redColor];
//    [selectedBackgroundView addSubview:lineLabel];
//    cell.selectedBackgroundView = selectedBackgroundView;//自定义cell选中时的背景

    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return kWIDTHS(50);
}
#pragma mark - 点击变红 [tableView点击方法]
// tableView点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    /**获取上一个indexPath */
    /**我们先设一个——selectIndex的NSIntge的变量，并给它置零，通过这个获取上一个我们点击的row */
    NSIndexPath * index = [NSIndexPath indexPathForItem:_selectIndex inSection:0];
    /**通过上一个row的值，获取上一个cell */
    UITableViewCell * oldCell = (UITableViewCell *)[tableView cellForRowAtIndexPath:index];
    
    /**改变上一个cell的颜色 */
    oldCell.textLabel.textColor = [UIColor grayColor];
    /**获取新的indexPath,直接通过点击方法中的indexPath来获取*/
    UITableViewCell * newCell = (UITableViewCell * )[tableView cellForRowAtIndexPath:indexPath];
    /**把点击的cell变成红色 */
    newCell.textLabel.textColor = UIColorFromRGB(0XFF2D47);
    /**点击完后，我们把刚刚点击的cell的row变为上一个（后去的cell的row）*/
    _selectIndex = indexPath.row;
    
    /** 参数1：需要进行滑动的控件（如：UITableView, UICollectionView）
     *  参数2：参数1 按IndexPath 进行滑动
     *  参数3：是否需要动画效果（YES or NO）
     */
    
    if (tableView == _tableView) {
        _isRelate = NO;
        [self.tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionMiddle];
        //将CollectionView的滑动范围调整到tableView相对应的cell的内容
        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:indexPath.row] atScrollPosition:UICollectionViewScrollPositionTop animated:YES];
    }
    
    
    /**计算cell的高度,_selectIndex为选择后的row */
//    _num = 0;
//    for (NSInteger i = 0; i < _selectIndex; i++) {
//
//        GiftBeforeModel * model = _zhongZhuanArr[i];
//        //        NSLog(@"%ld", model.dataArr.count);
//        _num = _num + (model.dataArr.count + 2) / 3;
//
//    }
#warning 注：
    /**算出要偏移的的距离 */
    //   kWIDTHCELL / 4 + kWIDTHS(20))算出一个品类中一个cell的高度
    //   _num * (kWIDTHCELL / 4 + kWIDTHS(20))算出一个品类中总的高度
    //   kWIDTHS(30) * indexPath.row因为每一个品类中都有一个分区头，我们必须将它加上
    //   最后得到的就是偏移量
//    CGFloat offset = _num * (kWIDTHCELL / 4 + kWIDTHS(20)) + kWIDTHS(30) * indexPath.row;
//
//    _collectionView.contentOffset = CGPointMake(0, offset);

}


#pragma mark = 创建CollectionView
- (void)createCollectionView{
    
    UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumInteritemSpacing = 0;
    layout.minimumLineSpacing = 0;
    layout.itemSize = CGSizeMake(kWIDTHCELL - _tableView.frame.size.width, kHEIGHTCELL);
    layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    self.collectionView = [[BaseCollectionView alloc] initWithFrame:CGRectMake(kWIDTHS(100), kWIDTHS(30), kWIDTHCELL - self.tableView.frame.size.width, kHEIGHTCELL) collectionViewLayout:layout];
    _collectionView.pagingEnabled = NO;
    [self.contentView addSubview:_collectionView];
    [_collectionView release];
    [layout release];
    
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    
    [_collectionView registerClass:[GongLvCollectionViewCell class] forCellWithReuseIdentifier:@"gongLvCell"];
    
    [_collectionView registerClass:[GiftCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
}

/** Cell的个数*/
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    GiftBeforeModel *model = _zhongZhuanArr[section];
    return model.dataArr.count;
}
/** 自定义Cell*/
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    GongLvCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"gongLvCell" forIndexPath:indexPath];
    
    GiftBeforeModel *model = _zhongZhuanArr[indexPath.section];
    cell.giftmodel = model.dataArr[indexPath.row];
    
    NSIndexPath *cruntindexPath = [[self.collectionView indexPathsForVisibleItems] lastObject];
    NSLog(@"%ld", (long)cruntindexPath.section);
    
    return cell;
}

#pragma mark - 分区数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return _zhongZhuanArr.count;
}

#pragma mark - 计算每个Cell的高度
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    /** 设置item尺寸*/
    if (indexPath.item == 0) {
        
    }
    return CGSizeMake((kWIDTHCELL - self.tableView.frame.size.width) / 3, kWIDTHCELL / 4 + kWIDTHS(20));
}

#pragma mark - 自定义分区头
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        
        GiftCollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];
        GiftBeforeModel *model = _zhongZhuanArr[indexPath.section];
        header.str = model.name;
        return header;
    }
    return nil;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    /** 设置组距离上向左右的间距*/
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    //两个item的列间距
    return 0;
}

-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    //如果一组中有多行item，设置行间距
    return 0;
}

#pragma mark - 分区头的 高度
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    
    return CGSizeMake(kWIDTHCELL, kWIDTHS(30));
}


#pragma mark - collectionView点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    NSLog(@"%zi组, %zi行", indexPath.section, indexPath.item);
    
    UIViewController *viewController = [self ViewController];
    
    GiftBeforeModel *model = _zhongZhuanArr[indexPath.section];
    GiftModel *gifModel = model.dataArr[indexPath.row];
    
    SZCHotViewController *hotVc = [[SZCHotViewController alloc] init];
    hotVc.num = gifModel.number;
    hotVc.titles = gifModel.name;
    hotVc.judge = @"gifContent";
    
    [viewController.navigationController pushViewController:hotVc animated:YES];
    [hotVc release];
}

- (UIViewController *)ViewController {
    
    for (UIView *next = [self superview]; next; next = next.superview) {
        UIResponder *nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController *)nextResponder;
        }
    }
    return nil;
}

#pragma mark - CollectionView 将显示视图
- (void)collectionView:(UICollectionView *)collectionView willDisplaySupplementaryView:(UICollectionReusableView *)view forElementKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath {
    
//    NSIndexPath *index = [NSIndexPath indexPathForRow:indexPath.section inSection:0];
//    
//    // 参数1:需要进行滑动的控件（如：UITableView、 UICollectionView）
//    // 参数2:参数1按 IndexPath 进行滑动
//    // 参数3:是否需要动画效果（YES or NO）
//    [self.tableView scrollToRowAtIndexPath:index atScrollPosition:UITableViewScrollPositionTop animated:YES];
    
    if (_isRelate) {
        NSInteger topcellsection = [[[collectionView indexPathsForVisibleItems] firstObject] section];
        
        if (collectionView == _collectionView) {
            [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForItem:topcellsection inSection:0] animated:YES scrollPosition:UITableViewScrollPositionMiddle];
        }
    }
}

#pragma mark - CollectionView 将结束显示视图
- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingSupplementaryView:(UICollectionReusableView *)view forElementOfKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath
{
//    /** 到TableView的第几个分区*/
//    NSIndexPath *index = [NSIndexPath indexPathForItem:indexPath.section inSection:0];
//    [self.tableView scrollToRowAtIndexPath:index atScrollPosition:UITableViewScrollPositionTop animated:YES];
    
    if (_isRelate) {
        NSInteger itemsection = [[[collectionView indexPathsForVisibleItems] firstObject] section];
        
        if (collectionView == _collectionView) {
            [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForItem:itemsection inSection:0] animated:YES scrollPosition:UITableViewScrollPositionMiddle];
        }
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    NSLog(@"ddddd");
//    _isRelate = YES;
}


//-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
//
//    if (scrollView == _collectionView) {
//        NSArray *indexArr = [_collectionView indexPathsForVisibleItems];
//        
//        NSIndexPath *midIndex = indexArr[indexArr.count/2];
//
//        NSIndexPath *tableIndex = [NSIndexPath indexPathForRow:midIndex.section inSection: 0];
//        
//        BaseTableViewCell *cell = (BaseTableViewCell *)[_tableView cellForRowAtIndexPath:tableIndex];
//        cell.textLabel.textColor = [UIColor grayColor];
//
//        [_tableView scrollToRowAtIndexPath:tableIndex atScrollPosition:(UITableViewScrollPositionMiddle) animated:YES];
//        
//    }
//}





@end
